1713C - Build Permutation - CodeForces Solution


constructive algorithms dp math *1200

Please click on ads to support us..

Python Code:

import math
t = int(input())

for i in range(t) : 
    n = int(input())
    lst = [j for j in range(n)]
    ed = n - 1
    while ed >= 0:
        tmp = int(math.ceil(math.sqrt(ed)))
        st = tmp * tmp - ed
        i1 = st
        i2 = ed
        while i1 < i2 : 
            lst[i1], lst[i2] = lst[i2], lst[i1]
            i1 += 1
            i2 += -1
        ed = st - 1
    for i in lst :
        print(i, end=" ")
    print("\n")

C++ Code:

#include <bits/stdc++.h>

using namespace std;

#define mp make_pair
#define pb push_back
#define int long long
#define pii pair<int, int>
#define fi first
#define se second
#define all(v) v.begin(), v.end()

#define trace(x) cout << '>' << #x << ':' << x << "\n"
#define trace2(x,y) cout<< '>' << #x << ':' << x << " | " << #y << ':' << y << "\n"
#define trace3(a,b,c) cout<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<"\n"
#define trace4(a,b,c,d) cout<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<"\n"

template <typename T>
void print(T var){
    cout << var << ' ';
    return;
}

template <typename T>
void print(vector <T> var){
    for (auto x: var)
        print(x);
    cout << "\n";
    return;
}

int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
const int mod = 1e9+7;

bool sq(int x) {
    int xx = sqrt(x);
    return (xx*xx==x);
}

signed main(){

    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int t;
    cin >> t;

    while (t--) {
        int n;
        cin >> n;
        vector<int> v(n);
        iota(all(v),0);
        for (int i = n-1; i >= 0; i--) {
            for (int j = i; j >= 0; j--) {
                if (sq(i+j)) {
                    reverse(v.begin()+j, v.begin()+i+1);
                    i = j;
                    break;
                }
            }
        }
        for (int i: v) cout << i << ' ';
        cout << '\n';
    }

}


Comments

Submit
0 Comments
More Questions

746. Min Cost Climbing Stairs
392. Is Subsequence
70. Climbing Stairs
53. Maximum Subarray
1527A. And Then There Were K
1689. Partitioning Into Minimum Number Of Deci-Binary Numbers
318. Maximum Product of Word Lengths
448. Find All Numbers Disappeared in an Array
1155. Number of Dice Rolls With Target Sum
415. Add Strings
22. Generate Parentheses
13. Roman to Integer
2. Add Two Numbers
515. Find Largest Value in Each Tree Row
345. Reverse Vowels of a String
628. Maximum Product of Three Numbers
1526A - Mean Inequality
1526B - I Hate 1111
1881. Maximum Value after Insertion
237. Delete Node in a Linked List
27. Remove Element
39. Combination Sum
378. Kth Smallest Element in a Sorted Matrix
162. Find Peak Element
1529A - Eshag Loves Big Arrays
19. Remove Nth Node From End of List
925. Long Pressed Name
1051. Height Checker
695. Max Area of Island
402. Remove K Digits